<template>
  <div>
    <div class="op-btns">
      <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" inline label-width="90px">
        <px-form-item label="时间" style="width: 430px">
          <px-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :clearable="false"
            :default-time="defaultTime"
            :disabled-time="disabledRangeTime"
            @focus="handleFocus"
            @calendar-change="handleCalendarChange"
          />
        </px-form-item>

        <div class="query-btn-group">
          <px-button type="primary" @click="searchAction">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
          <px-button type="primary" @click="exportAction">导出</px-button>
        </div>
      </px-form>
    </div>
    <chartsCheckbox ref="childRef1" title="VOC进口" onlineKey="MICH_004" leaveLineKey="" :ind="1" :dateRange="dateRange" />
    <chartsCheckbox ref="childRef2" title="VOC出口" onlineKey="MICH_004A" leaveLineKey="有机排" :ind="2" :dateRange="dateRange" />
    <chartsCheckbox ref="childRef3" title="VOC中酸碱" onlineKey="MICH_004B" leaveLineKey="有机排" :ind="3" :dateRange="dateRange" />
    <chartsCheckbox ref="childRef4" title="SEX中酸碱" onlineKey="MICH_004C" leaveLineKey="酸排" :ind="4" :dateRange="dateRange" />
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, watch } from "vue";
import chartsCheckbox from "@/views/machine/operation/voc/historyDataAnalysis/components/chartsCheckbox.vue";
import ExcelJS from "exceljs"; // 引入exceljs, 用于生成excel文件
import { saveAs } from "file-saver"; // 引入file-saver, 用于保存文件
import { PxMessage } from "px-ui"; // 引入file-saver, 用于保存文件

defineOptions({
  name: "MACHINE_AR"
});

const { proxy }: any = getCurrentInstance();

const queryParams = ref({});

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 3, 59, 59)];
const dateRange = ref([
  proxy.parseTime(new Date().getTime() - (1 * 60 * 60 * 1000 - 1000), "{y}-{m}-{d} {h}:{i}:{s}"),
  proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}")
]);

const currentSelecting = ref(null); // 记录当前正在选择的是开始还是结束时间

// 处理获取焦点事件
const handleFocus = e => {
  // 通过DOM判断点击的是开始还是结束输入框
  const targetClass = e.target.className;
  if (typeof targetClass === "string") {
    currentSelecting.value = targetClass.includes("start") ? "start" : "end";
  }
};

// 处理日历选择变化
const handleCalendarChange = dates => {
  if (dates && dates.length === 2) {
    const diff = new Date(dates[1]).getTime() - new Date(dates[0]).getTime();
    if (diff > 4 * 60 * 60 * 1000) {
      PxMessage.error("时间范围不能超过4小时");
    }
  }
};

// 严格限制时间选择范围
const disabledRangeTime = (date, type) => {
  // 如果没有选择开始时间或不是结束时间选择，不做限制
  if (!dateRange.value[0] || type !== "end") {
    return {};
  }

  const start = new Date(dateRange.value[0]);
  const maxEnd = new Date(start.getTime() + 4 * 60 * 60 * 1000);

  // 如果当前正在选择开始时间，不做限制
  if (currentSelecting.value === "start") {
    return {};
  }

  return {
    // 禁用小时
    disabledHours: () => {
      const disabledHours = [];
      const startHour = start.getHours();
      const maxHour = maxEnd.getHours();

      for (let i = 0; i < 24; i++) {
        // 禁用比开始时间早的小时
        if (i < startHour) {
          disabledHours.push(i);
        }
        // 禁用比最大结束时间晚的小时（如果是同一天）
        else if (date.getDate() === start.getDate() && i > maxHour) {
          disabledHours.push(i);
        }
        // 禁用比开始时间晚4小时以上的小时（如果是跨天）
        else if (date.getDate() > start.getDate() && i > maxHour) {
          disabledHours.push(i);
        }
      }
      return disabledHours;
    },

    // 禁用分钟
    disabledMinutes: selectedHour => {
      const disabledMinutes = [];
      const startHour = start.getHours();
      const startMinute = start.getMinutes();
      const maxHour = maxEnd.getHours();
      const maxMinute = maxEnd.getMinutes();

      // 如果是开始时间所在的小时，禁用之前的分钟
      if (selectedHour === startHour) {
        for (let i = 0; i < startMinute; i++) {
          disabledMinutes.push(i);
        }
      }

      // 如果是最大结束时间所在的小时，禁用之后的分钟
      if (selectedHour === maxHour) {
        for (let i = maxMinute + 1; i < 60; i++) {
          disabledMinutes.push(i);
        }
      }

      return disabledMinutes;
    },

    // 禁用秒（如果需要更精确的控制）
    disabledSeconds: (selectedHour, selectedMinute) => {
      const disabledSeconds = [];
      const startHour = start.getHours();
      const startMinute = start.getMinutes();
      const startSecond = start.getSeconds();
      const maxHour = maxEnd.getHours();
      const maxMinute = maxEnd.getMinutes();
      const maxSecond = maxEnd.getSeconds();

      // 如果是开始时间所在的小时和分钟，禁用之前的秒
      if (selectedHour === startHour && selectedMinute === startMinute) {
        for (let i = 0; i < startSecond; i++) {
          disabledSeconds.push(i);
        }
      }

      // 如果是最大结束时间所在的小时和分钟，禁用之后的秒
      if (selectedHour === maxHour && selectedMinute === maxMinute) {
        for (let i = maxSecond + 1; i < 60; i++) {
          disabledSeconds.push(i);
        }
      }

      return disabledSeconds;
    }
  };
};

// 监听时间范围变化
watch(dateRange, newVal => {
  if (newVal && newVal.length === 2) {
    const diff = new Date(newVal[1]).getTime() - new Date(newVal[0]).getTime();
    if (diff > 4 * 60 * 60 * 1000) {
      PxMessage.error("时间范围不能超过4小时");
    }
  }
});

const childRef1 = ref(null);
const childRef2 = ref(null);
const childRef3 = ref(null);
const childRef4 = ref(null);

const resetQuery = () => {
  dateRange.value = [
    proxy.parseTime(new Date().getTime() - (1 * 60 * 60 * 1000 - 1000), "{y}-{m}-{d} {h}:{i}:{s}"),
    proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}")
  ];
  searchAction();
};

const searchAction = () => {
  childRef1.value.getEcharts();
  childRef2.value.getEcharts();
  childRef3.value.getEcharts();
  childRef4.value.getEcharts();
};

const handleChangeTime = val => {
  console.log(val, "999999999999999999");
};

const exportChartToExcel = (chartRef, range, workbook, worksheet) => {
  const base64Image = chartRef.getDataURL({
    pixelRatio: 1, // 导出图片的分辨率比例，默认为1
    backgroundColor: "#fff" // 导出图片的背景色
  });
  let image = workbook.addImage({
    base64: base64Image, // 图片的base64编码
    extension: "png" // 图片的扩展名
  });
  worksheet.addImage(image, range); // 将图片添加到工作表中
};

// 导出
const exportAction = async () => {
  const workbook = new ExcelJS.Workbook(); // 创建工作簿
  const worksheet = workbook.addWorksheet("Sheet1"); // 添加工作表

  const echartsDom1 = await childRef1.value.getEchartsDom();
  const echartsDom2 = await childRef2.value.getEchartsDom();
  const echartsDom3 = await childRef3.value.getEchartsDom();
  const echartsDom4 = await childRef4.value.getEchartsDom();
  const startRow = 1;
  // 导出第一个图表
  exportChartToExcel(echartsDom1, `A${startRow}:N${30}`, workbook, worksheet);
  exportChartToExcel(echartsDom2, `A${startRow + 30}:N${60}`, workbook, worksheet);
  exportChartToExcel(echartsDom3, `A${startRow + 60}:N${90}`, workbook, worksheet);
  exportChartToExcel(echartsDom4, `A${startRow + 90}:N${120}`, workbook, worksheet);
  // 生成excel文件并保存
  workbook.xlsx.writeBuffer().then(function (buffer) {
    saveAs(
      new Blob([buffer], {
        type: "application/octet-stream"
      }),
      `历史数据分析_${new Date().getTime()}.xlsx`
    );
  });
};
</script>
<style scoped lang="scss">
.custom-form-ui {
  display: flex;
  align-items: center;
  height: 38px;

  .px-form-item {
    margin-bottom: 0;
  }
}

.op-btns {
  display: flex;
  padding: 16px 24px;
  margin-bottom: 16px;
  background-color: #fff;
  border-radius: 4px;

  .query-btn-group {
    display: flex;
  }

  .left {
    flex: 1;
    text-align: left;
  }

  .center {
    flex: 1;
    text-align: center;
  }

  .right {
    flex: 1;
    text-align: right;
  }
}

.footer-btns {
  text-align: right;
}
</style>
